import 'dart:async';

import 'coroutine.dart';

import '../other/result_extend.dart';

///请使用 job.delay
Future<void> delayFuture(int time) => Future.delayed(Duration(milliseconds: time));

///请使用 launchSJ
Timer timeRun(void Function() callback, [int? delay]) => Timer(delay == null ? Duration.zero : Duration(milliseconds: delay), callback);

///请使用 launchSJ
Timer taskLaunch(Function() function, {Function(ErrorInfo)? catchCall}) {
  return timeRun(() {
    runCatching(() => function()).onFailure((e) {
      catchCall?.call(e);
    });
  });
}

///请使用 launchSJ
Future<T> futureLaunch<T>(Future<T> Function() task) {
  return Future.microtask(task);
}

/// 管理多个任务
/// 无法在任务里面使用延迟，不然任务无法取消
/// 建议使用launch
class TaskManager {
  final Set<Completer> _tasks = {};

  Future run(Future Function() task, [Function? onError]) {
    final completer = Completer();
    _tasks.add(completer);

    Future wrappedTask() async {
      try {
        await task();
        completer.complete();
      } catch (e) {
        if (!completer.isCompleted) {
          completer.completeError(e);
        }
      } finally {
        _tasks.remove(completer);
      }
    }

    wrappedTask();
    //这里需要捕获异常，否则会抛出异常
    completer.future.catchError((e, s) {
      if (onError != null) {
        if (onError is dynamic Function(Object, StackTrace)) {
          onError(e, s);
        } else if (onError is dynamic Function(Object)) {
          onError(e);
        } else {
          onError();
        }
      }
    });
    return completer.future;
  }

  void cancel() {
    for (final completer in _tasks) {
      if (!completer.isCompleted) {
        completer.cancel();
      }
    }
    _tasks.clear();
  }
}

/// 定时器管理器
class TimeManager {
  final Map<Object, Timer> _timers = {};

  void run(Object taskId, int duration, Function() task) {
    final timer = Timer(Duration(milliseconds: duration), task);
    _timers[taskId] = timer;
  }

  void cancel(Object? taskId) {
    if (taskId == null) return;
    final timer = _timers[taskId];
    timer?.cancel();
    _timers.remove(taskId);
  }

  void cancelAll() {
    for (final taskId in _timers.keys.toList()) {
      cancel(taskId);
    }
  }
}

void main() async {
  // TaskManager taskManager = TaskManager();
  //
  // // 模拟添加多个异步任务
  // for (int i = 0; i < 5; i++) {
  //   taskManager.run(() async {
  //     await Future.delayed(Duration(seconds: 2));
  //     print('Task $i completed');
  //   });
  // }
  //
  // // 模拟在某个时机取消所有任务
  // await Future.delayed(Duration(seconds: 3));
  // taskManager.cancel();

  final task = taskLaunch(() async {
    print("futureLaunch run");
    await delayFuture(4000);
    print("111111111");
    return 1;
  });
  taskLaunch(() async {
    print("taskLaunch run");
    await delayFuture(2000);
    print("222222222");
    task.cancel();
  });
  print('All tasks cancelled');
}
